/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.swapper.regexp;

import java.util.Objects;
import java.util.Random;

/**
 * The regular expression concat node.
 * Match either left node and right node,
 * For example, in regular expression "ab",
 * left node is 'a', right node is 'b'.
 */
final class ConcatNode extends PatternNode {
  private final PatternNode left;
  private final PatternNode right;

  /**
   * Public constructor.
   *
   * @param context the generator context.
   * @param left    the left node.
   * @param right   the right node.
   * @throws NullPointerException if {@code left} or {@code right} is null.
   */
  public ConcatNode(PatternReverser context, PatternNode left, PatternNode right) {
    super(context);
    this.left = Objects.requireNonNull(left);
    this.right = Objects.requireNonNull(right);
  }

  /**
   * Gets the random weight.
   * The result is the product of the left and right nodes weight.
   *
   * @return the random weight.
   */
  @Override
  public int weight() {
    return left.weight() * right.weight();
  }

  @Override
  public String random(Random random) {
    return left.random(random) + right.random(random);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o instanceof ConcatNode) {
      ConcatNode that = (ConcatNode) o;
      return Objects.equals(left, that.left) && Objects.equals(right, that.right);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Objects.hash(left, right);
  }
}
